/**
 * @author: gao
 * @create-date: 2025/3/7 0:04
 */

public class MyHeap {
    public int[] elem;
    public int usedSize;

    public MyHeap() {
        elem = new int[10];
    }

    public void Initial(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void CreateHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            ShiftDown(parent, usedSize);
        }
    }

    private void ShiftDown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(parent,child);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void HeapSort(){
        int end = usedSize - 1;
        while (end > 0) {
            swap(0,end);
            ShiftDown(0,end);
            end--;
        }
    }
}